package Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;
import java.util.Properties;

/**
 *
 * @author rkppo
 */
public class count_HASH_code 
{
    public static String getHash(LinkedList<File> files) throws FileNotFoundException, IOException
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        int loop;
        for(loop=0;loop<files.size();loop++)
        {
            FileInputStream fis=new FileInputStream(files.get(loop));
            byte[] b = new byte[fis.available()];
            fis.read(b);
            bos.write(b);  
        }
        return returnHash(bos.toByteArray());
    }
    public static String getHash(File file) throws FileNotFoundException, IOException
    {
        if (file != null)
        {
            FileInputStream fis=new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
            byte[] b = new byte[fis.available()];
            fis.read(b);
            bos.write(b);  
            b=bos.toByteArray();
            return returnHash(b);
        }
        return null;
    }
    public static String getHash(String string) throws IOException
    {
        return returnHash(string.getBytes());
    }
    private static String returnHash(byte[] byteBuffer) 
    {
        Properties prop;
        String hash,hr;
        try {
            prop=new Properties();
            prop.load(new FileInputStream("src/Service/db_env_conf.properties"));
            hash=prop.getProperty("HASHmethod");
            } catch (Exception ex) {
            hash="SHA-256";
        }
            MessageDigest md;
            try {
                md = MessageDigest.getInstance(hash);
            } catch (NoSuchAlgorithmException ex) {
                return null;
            }
            md.update(byteBuffer);
            hr=new String(md.digest());
            return hr;
    }
}
